<template>
    <el-form ref="formRef" :model="form" :rules="ruleList" label-width="110px" label-position="left" :disabled="isDisable" class="my-bill-child-form" :class="{ 'my-bill-child-form_disabled': isDisable }">
      <div v-for="(item,index) in Datalist" :key="index">
            <scanTableForm v-if="item.el === 'ScanTable'" :tableData="item.tableData" :columns="item.columns" :showSelect="item.showSelect"/>
            <lineForm v-else-if="item.el === 'lineForm'" :text="item.label"/>
            <div style="display: flex;" v-else-if="item.el === 'uploadForm'">
              <uploadForm ref="uploadRef" :fileList="fileList" @on-submit="getUploadData"/>
              <!-- <span style="position: relative; top: 25px" v-if="isShowDifferent(item)" class="__ui_different">
                <el-icon><Warning /></el-icon>
              </span> -->
            </div>
            <div style="display: flex;" v-else-if="item.el === 'el-date-picker'">
              <scanPickerForm :label="item.label" :prop="item.prop" :picker-type="item.el" :value="pickerValue" @on-submit="(data) => {getPickerData(data, item.prop)}"/>
              <span style="position: relative; top: 6px" v-if="isShowDifferent(item)" class="__ui_different">
                <el-icon><Warning /></el-icon>
              </span>
            </div>
            <div style="display: flex;" v-else-if="item.el === 'el-time-picker'">
              <scanDateForm :label="item.label" :prop="item.prop" :picker-type="item.el" :value="timeValue" @on-submit="(data) => {getPickerData(data, item.prop)}"/>
              <span style="position: relative; top: 6px" v-if="isShowDifferent(item)" class="__ui_different">
                <el-icon><Warning /></el-icon>
              </span>
            </div>
            <el-form-item :label="item.label" :prop="item.prop" class="item" :label-width="item.labelWidth" v-else-if="item.el === 'el-select'">
              <el-select style="width: 100%" v-model="form[item.prop]" @change="(val) => selectChange(val, item)">
                <el-option v-for="(item, index) in item.option" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-row v-else-if="item.List">
                <el-col v-for="(item2,index) in item.List" :span="item2.rowWidth">
                    <el-form-item :label="item2.label"   :prop="item2.prop" class="item" :class="'item'+index" :label-width="item2.labelWidth">
                      <el-input v-if="item2.el === 'my-num-input'" v-model="form[item2.prop]" :placeholder="item2.placeholder" :disabled="item2.disabled" oninput ="value=value.replace(/[^\d.-]/g,'')" @change="(val) => singleItemChange(val, item)"></el-input>
                        <component v-else :is="item2.el" v-model="form[item2.prop]" :placeholder="item2.placeholder"></component>
                        <span v-if="isShowDifferent(item2)" class="__ui_different">
                          <el-icon><Warning /></el-icon>
                        </span>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-form-item v-else-if="item.el === 'my-num-input'" :label="item.label" :prop="item.prop" class="item" :label-width="item.labelWidth">
              <el-input v-model="form[item.prop]" :placeholder="item.placeholder" :disabled="item.disabled" oninput ="value=value.replace(/[^\d.-]/g,'')" @change="(val) => singleItemChange(val, item)"></el-input>
                <span v-if="isShowDifferent(item)" class="__ui_different">
                  <el-icon><Warning /></el-icon>
                </span>
            </el-form-item>
            <el-form-item v-else :label="item.label" :prop="item.prop" class="item" :label-width="item.labelWidth">
                <component :is="item.el" v-model="form[item.prop]" :placeholder="item.placeholder" :disabled="item.disabled" @change="(val) => singleItemChange(val, item)"></component>
                <span v-if="isShowDifferent(item)" class="__ui_different">
                  <el-icon><Warning /></el-icon>
                </span>
            </el-form-item>
          </div>
        <!-- <el-form-item> -->
        <ScanTableForm v-if="typeOptions[invoiceType].details" ref="ScanTableFormRef" :allListForm="allListForm" :detailListNew="detailListNew" :detailListBase="detailListBase" :isDisable="isDisable"></ScanTableForm>
        <!-- </el-form-item> -->
    </el-form>
</template>

<script  setup>
import { watch, nextTick } from 'vue'
import scanTableForm from './scanTableForm.vue'
import lineForm from './lineForm.vue'
import uploadForm from './uploadForm.vue'
import scanPickerForm from './scanPickerForm.vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Warning } from '@element-plus/icons-vue'
import { numAdd, numSub, numMulti } from '@/util'
import ScanTableForm from './scanTableForm.vue'
import ScanDateForm from './scanDateForm.vue'
import { typeOptions } from './typeList'
const props = defineProps({
  baseRatio: {
    // type: String || Number,
    default: ''
  },
  allListForm: {
    type: Object,
    default: () => {}
  },
  detailListNew: {
    type: Array,
    default: () => []
  },
  detailListBase: {
    type: Array,
    default: () => []
  },
    invoiceType: {
      type: Number,
      default: null
    },
    Datalist: {
        type: Array,
        default: []
    },
    ruleList: {
        type: Object,
        default: () => {}
    },
    BaseData: {
      type: Object,
        default: () => {}
    },
    FormData: {
        type: Object,
        default: () => {}
    },
    isDisable: {
        type: Boolean,
        default: false
    }
})

const form = ref({})
const formRef = ref(null)
const uploadRef = ref(null)
const ScanTableFormRef = ref(null)
const fileList = ref([])
const pickerValue = ref('')
const timeValue = ref('')
const emit = defineEmits(['on-submit'])

watch(()=> props.FormData, (newval) => {
    if(newval){
        form.value = {...props.FormData}
        // form.value = JSON.parse('{\"发票代码\":\"14403210911011\",\"发票名称\":\"啊啊啊\",\"发票号码\":\"No0796072411\",\"开票日期\":\"2022-03-01\",\"价税合计金额\":\"111\",\"附件\":[{\"fileName\":\"2.jpeg\",\"fileUrl\":\"https://img-test.sjgo365.com/fssc-product/888c9d80-bb3c-4f02-8178-b7b583557e26-20220315113031240.jpeg\"}]}')
        if ((props.invoiceType == 2 || props.invoiceType == 9) && !form.value['是否实名']) {
          form.value['是否实名'] = '是'
        }
        if (props.invoiceType == 2 && form.value['姓名']) {
          form.value['是否实名'] = '是'
        }
        if (props.invoiceType == 2) {
          form.value['开票日期'] = form.value['出发时间']
        }
        if(form.value['开票日期']){
            pickerValue.value = form.value['开票日期'] || ''
        }else{
            if(form.value['日期']){
              pickerValue.value = form.value['日期'] || ''
              form.value['开票日期'] = pickerValue.value
            }else{
              pickerValue.value = ''
            }
        }
        if (form.value['时间'] && props.invoiceType == 13) {
          timeValue.value = form.value['时间']
        }
        if (form.value['时间'] && props.invoiceType == 10) {
          timeValue.value = form.value['时间'] + ':00'
        }
        if(form.value['附件'] && form.value['附件'].length > 0){
            fileList.value = [...form.value['附件']]
            fileList.value.forEach((item)=>{
                if(item.fileName){
                    item.name = item.fileName
                }else{
                    item.name = item.name
                }
                if(item.fileUrl){
                  item.url = item.fileUrl
                }else{
                    item.url = item.url
                }
            })
        }else{
            fileList.value = []
        }
    }
},{immediate: true})

const getUploadData = (data)=>{
    form.value['附件'] = data
}

const getPickerData = (data, prop)=>{
    form.value[prop] = data
}

const resetValue = ()=>{
    formRef.value.resetFields()
}
const judgeDetailList = () => {
  return new Promise((resolve) => {
    if (props.invoiceType == 31) {
      resolve()
      // ScanTableFormRef.value.validateForm().then(res => {
      //   console.log(res, 'resresres')
      //   if (res) {
      //     resolve()
      //   }
      // })
    } else {
      resolve()
    }
  })
}
const saveFormData = () => {
    if (!formRef) return
    formRef.value.validate(valid => {
      console.log(valid, 'valid')
        if (valid) {
          judgeDetailList().then(() => {
            console.log('最终执行', form.value)
            emit('on-submit', {...form.value})
          })
            // emit('on-submit', {...form.value})
        } else {
            return false
        }
    })
}
const isShowDifferent = (item) => {
  let result = false
  if (props.BaseData && form.value && form.value[item.value] != props.BaseData[item.value] && props.isDisable && props.allListForm.inputBy == 1) {
    result = true
  }
  return result
}
const singleItemChange = (val, item) => {
  console.log('我变了')
  if (props.invoiceType == 2 || props.invoiceType == 5 || props.invoiceType == 9 || props.invoiceType == 10) {
    if (item.value === '票价' || item.value === '燃油附加费' || item.value === '民航发展基金') {
      const baseAmount = numAdd(form.value['票价'] || 0, form.value['燃油附加费'] || 0)
      const taxRatio = numMulti(form.value['税率'] ? parseFloat(form.value['税率']) : 0, 0.01)
      const taxAmount = numMulti(baseAmount / (numAdd(taxRatio, 1)), taxRatio)
      if (props.invoiceType == 5) {
        form.value['合计金额'] = numAdd(baseAmount, form.value['民航发展基金'])
        form.value['不含税票价'] = numSub(form.value['合计金额'] * 1, taxAmount * 1)
      } else {
        form.value['不含税票价'] = numSub(baseAmount * 1, taxAmount * 1)
      }
      form.value['税额'] = taxAmount
    }
  }
}
const selectChange = (val, item) => {
  // if (item.prop == '是否实名') {
  //   const baseAmount = numAdd(form.value['票价'] || 0, form.value['燃油附加费'] || 0)
  //   console.log(baseAmount, 'baseAmount')
  //   if (val == '是') {
  //     const taxAmount = numMulti(baseAmount / (numAdd(props.baseRatio, 1)), props.baseRatio)
  //     console.log(taxAmount, 'taxAmount')
  //     form.value['税额'] = taxAmount
  //     form.value['税率'] = numMulti(props.baseRatio, 100) + '%'
  //     form.value['不含税票价'] = numSub(baseAmount * 1, taxAmount * 1)
  //   } else {
  //     form.value['税额'] = 0
  //     form.value['税率'] = '0%'
  //     form.value['不含税票价'] = baseAmount * 1
  //   }
  // }
}
defineExpose({
  saveFormData,
  resetValue
})
</script>

<style lang="scss">
.dialog-footer{
    text-align: right;
}
.item .el-form-item__label{
    font-size: 14px;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 500;
    color: #6B728A;
}
.item1 .el-form-item__label {
  width: 80px!important;
    margin-left: 12px;
}
</style>
<style  lang="scss">
  .my-bill-child-form{
    .el-form-item__content{
      display: flex;
      flex-wrap: nowrap;
      flex-direction: column;
      justify-content: flex-start;
      align-items: flex-start;
      .el-form-item__error{
        position: relative;
        top: 0;
        left: 0;
      }
    }
    .__ui_different{
      margin-left: 5px;
      flex-shrink: 0;
      color: red;
    }
    .el-form-item--default{
      margin-bottom: 7px;
    }
    // .el-select{
    //   margin-bottom: 0;
    // }
  }
  .my-bill-child-form_disabled{
    .el-form-item__content{
      display: flex;
      flex-wrap: nowrap;
      flex-direction: row;
      align-items: center;
    }
  }
</style>
